package cn.blue.base.service.impl;

import cn.blue.base.config.BussinessException;
import cn.blue.base.constant.BaseConstants;
import cn.blue.base.dto.PhoneSmsCodeDto;
import cn.blue.base.service.IVerifyCodeService;
import cn.blue.base.util.SendSmsUtils;
import cn.blue.base.util.StrUtils;
import cn.blue.base.util.VerifyCodeUtils;
import cn.blue.user.domain.User;
import cn.blue.user.mapper.LogininfoMapper;
import cn.blue.user.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;
@Service
@Slf4j
public class VerifyCodeServiceImpl implements IVerifyCodeService {
        @Autowired
        private RedisTemplate redisTemplate;
        @Autowired
        private UserMapper userMapper;
        @Autowired
        private LogininfoMapper logininfoMapper;
    /**
     * 获取图形验证码
     * @param uuidKey
     * @return
     */
    @Override
    public String getImageCode(String uuidKey) {
        //生成随机数
        String randomCode = StrUtils.getComplexRandomString(4);
        //存入到redies
        redisTemplate.opsForValue().set(uuidKey,randomCode,3, TimeUnit.MINUTES);
        //生成图形验证码返回给前端
        return VerifyCodeUtils.VerifyCode(100,35,randomCode);
    }

    /**
     * 发送手机验证码
     * @param dto
     * UUID: imageCodeKey
     */
    @Override
    public void smsCode(PhoneSmsCodeDto dto) {
        if ("register".equals(dto.getType())){
            //验证参数是否为空
            //手机号格式todo自行验证
            //图形验证码是否正确
            verifyImgageCode(dto);
            // 两次发送短信间隔是否大于60s
            sendSmsCode(String.format(BaseConstants.VerfityCodeCons.REGISTER_SMSCODE_PHONE,dto.getPhone()));
        }else if ("binder".equals(dto.getType())){
            sendSmsCode(String.format(BaseConstants.VerfityCodeCons.BINDER_SMSCODE_PHONE,dto.getPhone()));
        }
    }



    private void sendSmsCode(String redisKey) {


        //俩次发送时间是否大于60秒
        //redis中key: register:smscode:phone value:验证码：时间戳
        String redisSmsCode = (String) redisTemplate.opsForValue().get(redisKey);
        //存在验证码用第一次的 不存在就生成新的验证码
        String smsCode = "";
        if(StringUtils.isNotBlank(redisSmsCode)){
            //不为空再做60秒校验 redisSmsCode   存的是验证码；时间戳
            String[] split = redisSmsCode.split(":");
            smsCode = split[0];
            //当前时间
            long newTime = System.currentTimeMillis();
            //redis中的时间 取出拼接时间为第一次发送验证码时间
            Long oldTime = Long.valueOf(split[1]);
            if(newTime - oldTime < 60*1000){
                throw new BussinessException("滚！");
            }
        }else {
            //生成验证码
            smsCode = StrUtils.getRandomString(4);
        }
        System.out.println(smsCode);
        String redisValue =  smsCode+":"+ System.currentTimeMillis();
        //存入到redis
        redisTemplate.opsForValue().set(redisKey,
        redisValue,5,TimeUnit.MINUTES);
        //发送短信
  //      SendSmsUtils.send(dto.getPhone(),"你好:你的验证码为:" + smsCode + ",五分钟有效");
    }



    private void verifyImgageCode(PhoneSmsCodeDto dto) {
        String imageCode = (String) redisTemplate.opsForValue().get(dto.getImageCodeKey());
        if(StringUtils.isBlank(imageCode) || !imageCode.equalsIgnoreCase(dto.getImageCodeValue())){{
            throw new BussinessException("图形验证码错误");
        }
        }
        //手机号是否存在
        User user = userMapper.findByPhone(dto.getPhone());
        if(null != user){
            throw new BussinessException("该手机号已存在");
        }
    }
}
